package com.seeTools.next.conf;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.seeTools.next.common.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author xiaotong
 */
@Slf4j
@Component
public class MybatisPlusBaseFieldsHandler implements MetaObjectHandler {

    /**
     * 设置数据新增时候的，字段自动赋值规则
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {

        try {
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            String loginName = tokenInfo != null ? tokenInfo.getLoginDevice() : "";
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            this.strictInsertFill(metaObject, "createBy", String.class, loginName);
            this.strictUpdateFill(metaObject, "updateBy", String.class, loginName);
        } catch (Exception e) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            this.strictInsertFill(metaObject, "createBy", String.class, Constants.ADMIN_LOGIN_NAME);
            this.strictUpdateFill(metaObject, "updateBy", String.class, Constants.ADMIN_LOGIN_NAME);
        } finally {
            this.strictInsertFill(metaObject, "tenantId", Long.class, 1L);
        }
    }

    /**
     * 设置数据修改update时候的，字段自动赋值规则
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            String loginName = tokenInfo != null ? tokenInfo.getLoginDevice() : "";
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            this.strictUpdateFill(metaObject, "updateBy", String.class, loginName);
        } catch (Exception e) {
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            this.strictUpdateFill(metaObject, "updateBy", String.class, Constants.ADMIN_LOGIN_NAME);
        }
    }
}
